﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Accout;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Account
{
    public class CreateAccountHandler : IRequestHandler<CreateAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;

        public CreateAccountHandler(IBaseRepository<AccountModel> accRepo,IMapper mapper)
        {
            this.accRepo = accRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加账号
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(CreateAccountCommand request, CancellationToken cancellationToken)
        {
            //包装响应结果
            ApiResult<int> result = new ApiResult<int>();

            //校验数据,检查是否已经存在改账号
            var acc = accRepo.GetAll().Where(x=>x.Name==request.Name).FirstOrDefault();
            if (acc != null) {
                //说明账号已经存在
                result.Code = ApiEnums.Error;
                result.Msg = "用户已经存在";
                result.Data = 0;
                return Task.FromResult(result);
            }

            // 把请求转换为model实体,补全实体数据
            var model = mapper.Map<AccountModel>(request);
            model.Id = YitIdHelper.NextId();
            model.Pass = request.Pass.GetMD5();
            //model.Pass = request.Pass.GetMD6();
            //调用仓储,把实体添加到数据库
            var r = accRepo.Create(model);

            if (r > 0)
            {
                result.Msg = "添加管理员账号成功!";
                result.Data = r;
                result.Code = ApiEnums.Success;
            }
            else {

                result.Msg = "添加管理员账号失败!";
                result.Data = r;
                result.Code = ApiEnums.Fail;
            }

            //用task封装响应结果并返回

            return Task.FromResult(result);
        }
    }
}
